package dao

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"mall_2.0/pkg/e"
	"mall_2.0/respository/db/model"
)

type CartDao struct {
	*gorm.DB
}

func NewCartDao(ctx context.Context) *CartDao {
	return &CartDao{NewDBClient(ctx)}
}

func NewCartDaoByDB(db *gorm.DB) *CartDao {
	return &CartDao{db}
}

// CreateCart 创建购物车，需要参数 商品ID（pID）、用户ID（uID）、卖家ID（bID）
func (dao *CartDao) CreateCart(pID, uID, bID uint) (cart *model.Cart, status int, err error) {
	// 查询有无此商品
	cart, err = dao.GetCartByID(pID, uID, bID)

	// 第一次加入
	if errors.Is(err, gorm.ErrRecordNotFound) {
		cart = &model.Cart{
			UserID:    uID,
			ProductID: pID,
			BossID:    bID,
			Num:       1,
			MaxNum:    10,
			Check:     false,
		}
		err = dao.DB.Model(&model.Cart{}).Create(&cart).Error
		if err != nil {
			return
		}
		return cart, e.SUCCESS, err
	}

	// 已加入，需要修改数量
	if cart.Num < cart.MaxNum {
		cart.Num++
		err = dao.DB.Model(&model.Cart{}).Save(&cart).Error
		if err != nil {
			return
		}
		return cart, e.ErrorProductExistCart, err
	}

	return cart, e.ErrorProductMoreCart, err
}

// GetCartByID 通过 商品ID（pID）、用户ID（uID）、卖家ID（bID） 获取购物车
func (dao *CartDao) GetCartByID(pID, uID, bID uint) (cart *model.Cart, err error) {
	err = dao.DB.Model(&model.Cart{}).Where("user_id = ? AND product_id = ? AND boss_id = ?", pID, uID, bID).First(&cart).Error
	return
}

// ListCartByUserID 根据用户ID获取购物车
func (dao *CartDao) ListCartByUserID(uID uint) (cart []*model.Cart, err error) {
	err = dao.DB.Model(&model.Cart{}).
		Joins("AS c LEFT JOIN product AS p ON c.product_id = p.id").
		Where("c.user_id = ?", uID).
		Select("c.id AS id," +
			"c.user_id AS user_id," +
			"c.product_id AS product_id," +
			"UNIX_TIMESTAMP(c.created_at) AS created_at," +
			"c.num AS num," +
			"c.max_num AS max_num," +
			"c.check AS check_," +
			"p.img_path AS img_path," +
			"p.boss_id AS boss_id," +
			"p.boss_name AS boss_name," +
			"p.info AS info," +
			"p.discount_price AS discount_price").
		Find(&cart).Error

	return
}

// UpdateCartNumByID 通过 ID 更新购物车的数量列
func (dao *CartDao) UpdateCartNumByID(uID, cID, num uint) error {
	return dao.DB.Model(&model.Cart{}).Where("id = ? AND user_id = ?", cID, uID).Update("num", num).Error
}

// DeleteCartByID 通过 购物车ID 删除购物车
func (dao *CartDao) DeleteCartByID(uID, cID uint) error {
	return dao.DB.Model(&model.Cart{}).Where("id = ? AND user_id = ?", cID, uID).Delete(&model.Cart{}).Error
}
